package com.ipDev.moyvSys.controller.user;


import com.ipDev.moyvSys.constant.JwtClaimsConstant;
import com.ipDev.moyvSys.domain.dto.UserLoginDTO;
import com.ipDev.moyvSys.domain.po.User;
import com.ipDev.moyvSys.domain.vo.UserLoginVO;
import com.ipDev.moyvSys.mapper.UserMapper;
import com.ipDev.moyvSys.properties.JwtProperties;
import com.ipDev.moyvSys.service.IUserService;
import com.ipDev.moyvSys.utils.JwtUtil;
import com.ipDev.moyvSys.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author fish
 * @since 2024-10-20
 */
@RestController
@RequestMapping("/user/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final IUserService userService;

    private final JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {

        log.info("用户登录:{}", userLoginDTO);
        User user = userService.login(userLoginDTO);
        log.info("login返回:{}",user);

        //登录成功后 给用户分发令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO vo = UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .name(user.getName())
                .token(token)
                .build();

        return Result.success(vo);
    }
}
